import { memo, useState } from 'react'
import styles from './index.module.scss'
import { Button, Typography, Space, Input, message } from 'antd'
import { LeftOutlined, EditOutlined } from '@ant-design/icons'
import { useNavigate, useParams } from 'react-router-dom'
import EditToolbar from './EditToolbar'
import useGetPageInfo from '@/hooks/useGetPageInfo'
import useGetComponentInfo from '@/hooks/useGetComponentInfo'
import { changePageTitle } from '@/store/modules/pageInfoReducer'
import { useDispatch } from 'react-redux'
import { api_updateQuestionById } from '@/api'
import { useRequest, useKeyPress, useDebounceEffect } from 'ahooks'

const { Title } = Typography

const TitleElement = memo(() => {
  const { title } = useGetPageInfo()
  const [editState, setEditState] = useState(false)
  const dispatch = useDispatch()

  const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newTitle = e.target.value
    if (!newTitle) return
    dispatch(changePageTitle(newTitle))
  }

  if (editState)
    return (
      <Input
        value={title}
        onChange={handleTitleChange}
        onBlur={() => setEditState(false)}
        onPressEnter={() => setEditState(false)}
      />
    )

  return (
    <Space>
      <Title>{title}</Title>
      <Button icon={<EditOutlined />} type="text" onClick={() => setEditState(true)}></Button>
    </Space>
  )
})

const SaveButton = memo(() => {
  const { id } = useParams()
  const { componentList = [] } = useGetComponentInfo()
  const pageInfo = useGetPageInfo()

  const { run } = useRequest(
    async () => {
      if (!id) return
      await api_updateQuestionById(id, { ...pageInfo, componentList })
    },
    {
      manual: true,
    }
  )
  useKeyPress(['ctrl.s', 'meta.s'], (e: KeyboardEvent) => {
    e.preventDefault()
    run()
  })

  // 自动保存
  useDebounceEffect(
    () => {
      run()
    },
    [componentList, pageInfo],
    { wait: 1000 }
  )

  return <Button onClick={run}>保存</Button>
})

const PublishButton = memo(() => {
  const nav = useNavigate()
  const { id } = useParams()
  const { componentList = [] } = useGetComponentInfo()
  const pageInfo = useGetPageInfo()

  const { run } = useRequest(
    async () => {
      if (!id) return
      await api_updateQuestionById(id, { ...pageInfo, componentList, isPublished: true })
      message.success('发布成功')
      nav(`/question/stat/${id}`)
    },
    {
      manual: true,
    }
  )
  return (
    <Button onClick={run} type="primary">
      发布
    </Button>
  )
})

const EditHeader = memo(() => {
  const nav = useNavigate()

  return (
    <div className={styles.header}>
      <div className={styles.left}>
        <Space align="center">
          <Button type="link" icon={<LeftOutlined />} onClick={() => nav(-1)}>
            返回
          </Button>
          <TitleElement />
        </Space>
      </div>
      <div className={styles.content}>
        <EditToolbar />
      </div>
      <div className={styles.right}>
        <Space>
          <SaveButton />
          <PublishButton />
        </Space>
      </div>
    </div>
  )
})

export default EditHeader
